let isDirty = false;

$('#save_success').text("");
$('#save').click(function () {
    if (!isDirty) return;
    let mapping_urls = $("#mapping-wrapper form input").toArray().map(v => $(v).val());
    let mapping_type = $("#mapping-wrapper form select").toArray().map(v => $(v).val());
    $("#status").removeClass("has-success");
    $("#status").removeClass("has-error");
    let mappings = [];
    mapping_urls.forEach((regexp, i) => {
        let folder = mapping_type[i];
        mappings.push([
            regexp,
            folder,
        ]);
    });

    chrome.storage.sync.set({
        [StorageKey.MUTE_MAPPINGS]: JSON.stringify(mappings),
    }, function () {
        $("#status").addClass("has-success");
        $('#save_success').text("Save successfully!");
        setTimeout(() => {
            $('#save_success').text("");
        }, 2000);
    });
    
    resetDirty();
});

chrome.storage.sync.get(StorageKeys, function (result) {
    let mappings = JSON.parse(result[StorageKey.MUTE_MAPPINGS] || "[]");
    mappings.forEach(v => {
        createMappingRule(v[0], v[1]);
    });
});

$("#add-mapping-rule").click(function () {
    createMappingRule('');
    setDirty();
});


function setDirty() {
    if (isDirty) return;
    isDirty = true;
    $("#save").toggleClass("btn-success btn-default");
}

function resetDirty() {
    if (!isDirty) return;
    isDirty = false;
    $("#save").toggleClass("btn-success btn-default");
}


function createMappingRule(url, type) {
    $("#mapping-wrapper").append(`
    <form class="form-horizontal" >
        <button type="button" class="btn btn-danger pull-right"><img src="/assets/remove.png"></button>
        <p class="clearfix"></p>
        <div class="form-group" >
            <label class="col-sm-3 control-label">URL</label>
            <div class="col-sm-9">
                <input class="form-control" rows="6" value="${url}" placeholder='URL likes https://www.bilibili.com/'></input>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">MuteType</label>
            <div class="col-sm-9">
                <select class="form-select" style="width: 100%; height: 2em;">
                    ${MuteTypes.map(muteType => {
                        return `<option value="${muteType}" ${ type == muteType ? "selected" : ""}>${muteType}</option>"`
                    })}
                </select>
            </div>
        </div>
    </form>
    `);
    $("#mapping-wrapper button.btn-danger").last().click(function(event) {
        event.currentTarget.parentNode.remove();
        setDirty();
    });
    $("#mapping-wrapper input").last().change(setDirty);
    $("#mapping-wrapper select").last().change(setDirty);
}

$(window).on('beforeunload', function(){
    return isDirty || undefined;
});